﻿// <copyright file="CoverageAggregate.aspx.cs" >
// Copyright (c) 2009 All Right Reserved
// </copyright>
// <author>Yuvaraj Ilangovan</author>
// <date>2009-07-14</date>
// <summary>Contains UI logic for showing code coverage aggregate report</summary>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RepRef;
using System.Data;
using System.Configuration;
//using Gios.Pdf;

//using iTextSharp.text;
//using iTextSharp.text.pdf;
//using iTextSharp.text.html;
//using iTextSharp.text.html.simpleparser;
using System.Text;

//using CrystalDecisions.CrystalReports;
//using CrystalDecisions.Shared;
//using CrystalDecisions.CrystalReports.Engine;
using System.Data.Common; 

public partial class ContentPages_CoverageAggregate : System.Web.UI.Page
{
    RepRef.IsimpleWcfClient aggrProxy;

    RepRef.StatisticsReport ststReport;
    RepRef.ModuleManager mgr;
    IList<RepRef.NamespaceInfo> namespaceCollection;
    string strXMLPath;
    public static bool showImage = false;

    public string ProjectName
    {
        get
        {
            string _projName = string.Empty;
            if (Session["ProjName"] != null)
            {
                _projName = Convert.ToString(Session["ProjName"]);
            }
            else
            {
                _projName = ConfigurationManager.AppSettings["ProjName"].ToString();
            }
            return _projName;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        lblprojName.Text = this.ProjectName;
        Session["ClsCovParameters"] = null;
        if (!IsPostBack)
        {
            if (Session["RptXMLPath"] != null)
            {
                strXMLPath = Session["RptXMLPath"].ToString();
            }
            if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
            {
                if (!string.IsNullOrEmpty(Request.QueryString["mod"]))
                {
                    LoadModLevelStastistics(Request.QueryString["mod"].ToString(), strXMLPath);
                    LoadModLevelNmsStatistics(Request.QueryString["mod"].ToString(), strXMLPath);
                    LoadModLevelNmsAggregate(Request.QueryString["mod"].ToString(), strXMLPath);
                }
            }
            else
            {
                LoadApplicationStatistics(strXMLPath);
                LoadAllNamesLevelReport(strXMLPath);
                LoadCovAggrAppLevel(strXMLPath);
            }


        }
    }
    protected void LoadApplicationStatistics(string strXMLPath)
    {
        try
        {
            aggrProxy = new IsimpleWcfClient();
            mgr = aggrProxy.ParseXmlObject(strXMLPath);
            ststReport = aggrProxy.GetStatetics(strXMLPath);
            lblCovLines.Text = ststReport.LOC.ToString();
            lblParCovLines.Text = ststReport.PLOC.ToString();
            lblCovBlocks.Text = ststReport.BlocksCov.ToString();
            lblNCLines.Text = ststReport.NCLOC.ToString();
            lblNCBlocks.Text = ststReport.BlocksNt.ToString();
            lblStatsName.Text = this.ProjectName;
            lblCovClasses.Text = mgr.CoveredClsCount.ToString();
            lblNClasses.Text = mgr.NCoverdClsCount.ToString();
            lblMethodsPerClass.Text = string.Format("{0:#.##}", mgr.AvgMethodClass);
            lblTime.Text = mgr.FileCreationTime.ToString();


        }
        catch (Exception ex)
        {
        }
    }
    protected void LoadModLevelStastistics(string modName, string strXMLPath)
    {
        try
        {
            aggrProxy = new IsimpleWcfClient();
            mgr = aggrProxy.ParseXmlObject(strXMLPath);
            ststReport = aggrProxy.GetStateticsBymodule(modName, strXMLPath);
            lblCovLines.Text = ststReport.LOC.ToString();
            lblParCovLines.Text = ststReport.PLOC.ToString();
            lblCovBlocks.Text = ststReport.BlocksCov.ToString();
            lblNCLines.Text = ststReport.NCLOC.ToString();
            lblNCBlocks.Text = ststReport.BlocksNt.ToString();
            lblStatsName.Text = ststReport.Name;
            lblCovClasses.Text = ststReport.TotClsCov.ToString();
            lblNClasses.Text = ststReport.TotNClsCov.ToString();
            lblMethodsPerClass.Text = string.Format("{0:#.##}", ststReport.AvgMtdClass);
            lblTime.Text = mgr.FileCreationTime.ToString();
        }
        catch (Exception ex)
        {

        }
    }
    protected void LoadModLevelNmsStatistics(string ModName, string strXMLPath)
    {
        try
        {
            IList<RepRef.NamespaceInfo> modNSCollection;
            aggrProxy = new IsimpleWcfClient();
            mgr = aggrProxy.ParseXmlObject(strXMLPath);
            modNSCollection = aggrProxy.GetNamespaceInfoAllByModule(ModName, strXMLPath);
            DataTable dtTable = CreateDataTable(modNSCollection);
            Session["DataTable"] = dtTable;
            DataView dv = new DataView(dtTable);
            dv.Sort = "NsCovPercentage ASC";
            gvAllNmspAgg.DataSource = dv;
            gvAllNmspAgg.DataBind();

        }
        catch (Exception ex)
        {
        }
    }
    protected void LoadModLevelNmsAggregate(string ModName, string strXMLPath)
    {
        try
        {
            IList<RepRef.ModNamespaceInfoAggr> modNSCollection;
            aggrProxy = new IsimpleWcfClient();
            mgr = aggrProxy.ParseXmlObject(strXMLPath);
            modNSCollection = aggrProxy.GetModLevelNamespaceAggReport(ModName, strXMLPath);
            gvCovAggregate.DataSource = modNSCollection;
            gvCovAggregate.DataBind();

        }
        catch (Exception ex)
        {
        }
    }
    protected void LoadCovAggrAppLevel(string strXMLPath)
    {
        try
        {
            IList<RepRef.ModuleManager> mgrList = new List<RepRef.ModuleManager>();
            aggrProxy = new IsimpleWcfClient();
            mgr = aggrProxy.ParseXmlObject(strXMLPath);
            mgrList.Add(mgr);
            gvCovAggregate.DataSource = mgrList;
            gvCovAggregate.DataBind();
        }
        catch (Exception ex)
        {
        }
    }
    protected void LoadAllNamesLevelReport(string strXMLPath)
    {
        try
        {
            aggrProxy = new IsimpleWcfClient();
            mgr = aggrProxy.ParseXmlObject(strXMLPath);
            namespaceCollection = aggrProxy.GetNamespaceInfoAll(strXMLPath);
            DataTable dtTable = CreateDataTable(namespaceCollection);
            Session["DataTable"] = dtTable;
            DataView dv = new DataView(dtTable);
            dv.Sort = "NsCovPercentage ASC";
            gvAllNmspAgg.DataSource = dv;
            gvAllNmspAgg.DataBind();
        }
        catch (Exception ex)
        {
        }
    }
    public string TruncateDouble(double dblValue)
    {
        string strPercent = string.Format("{0:0.##}", dblValue);
        return strPercent + "%";
    }
    public int SetLblMajorWidth(double dblValue)
    {
        int major = Convert.ToInt32(Math.Round(dblValue));
        return Convert.ToInt16((major / 2));
    }
    public int SetLblMinorWidth(double dblValue)
    {
        int minor = (100 - (Convert.ToInt32(Math.Round(dblValue))));
        return Convert.ToInt16((minor / 2));
    }
    protected void gvAllNmspAgg_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "LoadMaster":
                int rowIndex;
                if (int.TryParse(e.CommandArgument.ToString(), out rowIndex))
                {
                    Label lblMod = (Label)gvAllNmspAgg.Rows[rowIndex].FindControl("lblModName");
                    LinkButton lb = (LinkButton)gvAllNmspAgg.Rows[rowIndex].FindControl("lnkNsname");
                    Session["ClsCovParameters"] = lblMod.Text + "," + lb.Text;
                    string strPath = "../ContentPages/NamespaceClassReport.aspx?mod1=" + lblMod.Text + "&nName=" + lb.Text;
                    //Server.Transfer(strPath);
                    Response.Redirect(strPath);
                }
                break;
            case "OpenCloud":
                if (int.TryParse(e.CommandArgument.ToString(), out rowIndex))
                {
                    if (Session["RptXMLPath"] != null)
                    {
                        strXMLPath = Session["RptXMLPath"].ToString();
                    }

                    Label lblMod = (Label)gvAllNmspAgg.Rows[rowIndex].FindControl("lblModName");
                    LinkButton lb = (LinkButton)gvAllNmspAgg.Rows[rowIndex].FindControl("lnkNsname");
                    Session["ClsCovParameters"] = lblMod.Text + "," + lb.Text;
                    string strPath = "../ContentPages/CoverageCloud.aspx?mod1=" + lblMod.Text + "&nName=" + lb.Text + "&rptLink=" + strXMLPath;
                    Response.Redirect(strPath);
                }
                break;

        }

    }
    protected void gvCovAggregate_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string strPath = string.Empty;
        switch (e.CommandName)
        {
            case "OpenCloud":
                int rowIndex;
                if (int.TryParse(e.CommandArgument.ToString(), out rowIndex))
                {
                    if (Session["RptXMLPath"] != null)
                    {
                        strXMLPath = Session["RptXMLPath"].ToString();
                    }
                    ImageButton img = (ImageButton)gvCovAggregate.Rows[rowIndex].FindControl("imgCloud");
                    if (!string.IsNullOrEmpty(Request.QueryString["mod"]))
                    {

                        strPath = "../ContentPages/CoverageCloud.aspx?modname=" + Request.QueryString["mod"].ToString() + "&rptLink=" + strXMLPath;
                    }
                    else
                    {
                        strPath = "../ContentPages/CoverageCloud.aspx?rptLink=" + strXMLPath;
                    }
                    //Server.Transfer(strPath);
                    Response.Redirect(strPath);
                }
                break;
        }

    }
    protected void gvAllNmspAgg_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (Session["DataTable"] != null)
        {
            DataTable dtTable = (DataTable)Session["DataTable"];
            if (dtTable != null)
            {
                dtTable.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                gvAllNmspAgg.DataSource = dtTable;
                gvAllNmspAgg.DataBind();
            }
        }
    }
    private string GetSortDirection(string column)
    {

        // By default, set the sort direction to ascending.
        string sortDirection = "ASC";

        // Retrieve the last column that was sorted.
        string sortExpression = ViewState["SortExpression"] as string;

        if (sortExpression != null)
        {
            // Check if the same column is being sorted.
            // Otherwise, the default value can be returned.
            if (sortExpression == column)
            {
                string lastDirection = ViewState["SortDirection"] as string;
                if ((lastDirection != null) && (lastDirection == "ASC"))
                {
                    sortDirection = "DESC";
                }
            }
        }

        // Save new values in ViewState.
        ViewState["SortDirection"] = sortDirection;
        showImage = true;
        ViewState["SortExpression"] = column;

        return sortDirection;
    }
    private DataTable CreateDataTable(IList<NamespaceInfo> nsInfoColln)
    {
        DataTable dtTable = new DataTable();
        dtTable.Columns.Add("ModuleName", typeof(string));
        dtTable.Columns.Add("NamespaceName", typeof(string));
        dtTable.Columns.Add("NsCovPercentage", typeof(double));
        dtTable.Columns.Add("AvgClsFile", typeof(double));
        dtTable.Columns.Add("AvgMtdClass", typeof(double));
        dtTable.Columns.Add("TotFiles", typeof(int));
        dtTable.Columns.Add("TotClasses", typeof(int));
        dtTable.Columns.Add("CovLines", typeof(int));
        dtTable.Columns.Add("NCLines", typeof(int));

        foreach (NamespaceInfo nInfo in nsInfoColln)
        {
            DataRow dtRow = dtTable.NewRow();
            dtRow["ModuleName"] = nInfo.ModuleName;
            dtRow["NamespaceName"] = nInfo.NamespaceName;
            dtRow["NsCovPercentage"] = nInfo.NsCovPercentage;
            dtRow["AvgClsFile"] = nInfo.AvgClsFile;
            dtRow["AvgMtdClass"] = nInfo.AvgMtdClass;
            dtRow["TotFiles"] = nInfo.TotFiles;
            dtRow["TotClasses"] = nInfo.TotClasses;
            dtRow["CovLines"] = nInfo.CovLines;
            dtRow["NCLines"] = nInfo.NCLines;
            dtTable.Rows.Add(dtRow);
        }
        return dtTable;
    }
    protected void AddSortImage(GridViewRow HeaderRow, int colIndex)
    {
        System.Web.UI.WebControls.Image sortImage = new System.Web.UI.WebControls.Image();
        sortImage.CssClass = "SortImageStyle";
        //ViewState["SortDirection"] = GetSortDirection(column);
        if (showImage) // this is a boolean variable which should be false 
        {            //  on page load so that image wont show up initially.


            if (ViewState["SortDirection"] != null)
            {
                if (ViewState["SortDirection"].ToString() == "ASC")
                {

                    sortImage.ImageUrl = "/CoverageReport/App_Themes/ReportThemes/images/White_GrayDown.png";
                    sortImage.AlternateText = " Ascending Order";
                }

                else
                {
                    sortImage.ImageUrl = "/CoverageReport/App_Themes/ReportThemes/images/White_GrayUp.png";
                    sortImage.AlternateText = " Descending Order";
                }

                HeaderRow.Cells[colIndex].Controls.Add(sortImage);
            }
        }

    }
    protected void gvAllNmspAgg_RowCreated(object sender, GridViewRowEventArgs e)
    {
        //int sortColumnIndex = 0;

        if (e.Row.RowType == DataControlRowType.Header)
        //sortColumnIndex = GetSortColumnIndex();
        {
            string sortExprn = string.Empty;
            if (ViewState["SortExpression"] != null)
            {
                sortExprn = ViewState["SortExpression"].ToString();
            }
            int index = findColumnIndex(sortExprn);
            AddSortImage(e.Row, index);


        }


    }
    //protected int GetSortColumnIndex()
    //{
    //    foreach (DataControlField field in gvAllNmspAgg.Columns)
    //    {
    //        //gvAllNmspAgg.SortExpression = sortExprn;
    //        if (field.SortExpression == gvAllNmspAgg.SortExpression)
    //            return gvAllNmspAgg.Columns.IndexOf(field);
    //        else
    //            return -1;
    //    }
    //    return -1;
    //}
    private int findColumnIndex(string accessibleHeaderText)
    {
        for (int index = 0; index < gvAllNmspAgg.Columns.Count; index++)
        {
            if (String.Compare(gvAllNmspAgg.Columns[index].SortExpression, accessibleHeaderText, true) == 0)
            {
                return index;
            }
        }
        return -1;
    }
    //public string GetSortColumn()
    //{
    //    string exprn = string.Empty;
    //    foreach (DataControlField field in gvAllNmspAgg.Columns)
    //    {
    //        if (field.SortExpression == gvAllNmspAgg.SortExpression)
    //        {
    //            exprn =  gvAllNmspAgg.SortExpression; 
    //        }
    //    }
    //    return exprn; 
    //}
    protected void gvAllNmspAgg_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl = ((Label)e.Row.FindControl("lbltotcov"));
            LinkButton lnkns = ((LinkButton)e.Row.FindControl("lnkNsname"));
            ImageButton img = ((ImageButton)e.Row.FindControl("imgCloud"));
            System.Web.UI.HtmlControls.HtmlTableCell TCell = ((System.Web.UI.HtmlControls.HtmlTableCell)e.Row.FindControl("tdTotCov"));
            string[] strArr = null;
            if (!string.IsNullOrEmpty(lbl.Text))
            {
                strArr = lbl.Text.Split('%');
                if (Convert.ToDouble(strArr[0].ToString()) < 75.0)
                {
                    TCell.BgColor = "#FF0000";

                }
            }
            if (!string.IsNullOrEmpty(lnkns.Text))
            {
                img.ToolTip = "Tag cloud report for " + lnkns.Text;
            }
        }
    }
    protected void gvCovAggregate_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            if (Request.QueryString["mod"] != null)
            {
                e.Row.Cells[0].Text = Request.QueryString["mod"].ToString();
            }
            else
            {
                e.Row.Cells[0].Text = this.ProjectName;
            }
        }
        else if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblcov = ((Label)e.Row.FindControl("lbltotcov"));
            System.Web.UI.HtmlControls.HtmlTableCell TCell = ((System.Web.UI.HtmlControls.HtmlTableCell)e.Row.FindControl("totCover"));
            string[] strArr = null;
            if (!string.IsNullOrEmpty(lblcov.Text))
            {
                strArr = lblcov.Text.Split('%');
                if (Convert.ToDouble(strArr[0].ToString()) < 75.0)
                {
                    TCell.BgColor = "#FF0000";
                }
            }
        }
    }
    //protected void Button1_Click(object sender, EventArgs e)
    //{
    //    //if (Session["RptXMLPath"] != null)
    //    //{
    //    //    strXMLPath = Session["RptXMLPath"].ToString();
    //    //}
    //    //PrintPDF(strXMLPath);
      
    //}
    protected void PrintPDF(string strXMLPath)
    {
        //    //IList<RepRef.NamespaceInfo> modNSCollection;
        //    //modNSCollection = aggrProxy.GetNamespaceInfoAllByModule(ModName, strXMLPath);
        //    //DataTable dtTable = CreateDataTable(modNSCollection);

        //    aggrProxy = new IsimpleWcfClient();
        //    mgr = aggrProxy.ParseXmlObject(strXMLPath);
        //    namespaceCollection = aggrProxy.GetNamespaceInfoAll(strXMLPath);
        //    DataTable dtTable = CreateDataTable(namespaceCollection);
        //    PdfDocument myDoc = new PdfDocument(PdfDocumentFormat.InCentimeters(21, 29.7));
        //    PdfTable myTable = myDoc.NewTable(new System.Drawing.Font("Verdana", 12), 200, 9, 4);
        //    myTable.ImportDataTable(dtTable);
        //    myTable.HeadersRow.SetColors(System.Drawing.Color.White, System.Drawing.Color.Navy);
        //    myTable.SetColors(System.Drawing.Color.Black, System.Drawing.Color.White, System.Drawing.Color.Gainsboro);
        //    myTable.SetBorders(System.Drawing.Color.Black, 1, BorderType.CompleteGrid);
        //    myTable.SetColumnsWidth(new int[] {5,25,16,20,20,15});
        //    myTable.SetContentAlignment(System.Drawing.ContentAlignment.MiddleCenter);
        //    while (!myTable.AllTablePagesCreated)
        //    {
        //        PdfPage newPage = myDoc.NewPage();
        //        PdfTablePage newTabPage = myTable.CreateTablePage(new PdfArea(myDoc, 48, 120, 500.0, 670.0));

        //        PdfTextArea pta = new PdfTextArea(new System.Drawing.Font("Verdana", 26, System.Drawing.FontStyle.Bold),System.Drawing.Color.Red,new PdfArea(myDoc,0,20,595,120),System.Drawing.ContentAlignment.MiddleCenter,"Aggregate Summary");

        //        newPage.Add(newTabPage);
        //        newPage.Add(pta);

        //        //for (int index = newTabPage.FirstRow; index <= newTabPage.LastRow; index++)
        //        //    if (((DateTime)myTable.Rows[index][2].Content).Year == 1968)
        //        //    {
        //        //        PdfCircle pc = newTabPage.CellArea(index, 2).InnerCircle(System.Drawing.Color.Blue, 2);
        //        //        pc.StrokeWidth = 3.5;
        //        //        newPage.Add(pc);
        //        //    }

        //        newPage.SaveToDocument();
        //    }
        //    myDoc.SaveToFile(@"C:\Yuvaraj\Code\MSCoverageReport\CoverageReport\AggregateSummary.pdf");
        //}
    }

    
}






